package com.erpanderp.wam.usm.view.user;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import com.erpanderp.wam.adm.model.entity.Role;
import com.erpanderp.wam.adm.model.service.ModuleDAO;
import com.erpanderp.wam.adm.model.service.RoleDAO;
import com.erpanderp.wam.usm.model.entity.leave.LeaveBalance;
import com.erpanderp.wam.usm.model.entity.leave.LeaveType;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.entity.user.EmployeeAndReporting;
import com.erpanderp.wam.usm.model.entity.user.EmployeeRole;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.leave.LeaveTypeDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMPasswordUtil;

@ManagedBean
@ViewScoped
public class RegisterAdminBean implements Serializable{

	private static final long serialVersionUID = 1L;

	private Employee employee = new Employee();
	private EmployeeAndReporting employeeAndReporting = new EmployeeAndReporting();
	private WAMUser wamUser = new WAMUser();
	private String reenteredPassword;
	
    ModuleDAO moduleDAO = new ModuleDAO();
    EmployeeDAO employeeDAO = new EmployeeDAO();
    RoleDAO roleDAO = new RoleDAO();
    
    private Long selectedModuleId;
    private List<Employee> registeredEmployeesList = new ArrayList<Employee>();
    
    
    boolean REGISTERED;   
    boolean FORM_VALID;
    
	public RegisterAdminBean(){
		System.out.println("EMPLOYEE REGISTRATION BEAN INTIALIZING...");
		//employee.setEmployeeCode(employeeDAO.generateEmployeeCode());		
	}
	
	public void saveAdmin(){
		validateForm();
		
		if(FORM_VALID){
			try{
				System.out.println("SAVE ADMIN");
				Date now = new Date();
				employee.setEmployeeCode("admin");
				employee.setAuthentication(CommonLookup.AUTHENTICATION_YES);
				employee.setModuleName("Prime");
				employee.setDesignation("Primefaces Consultant");
				employee.setCreateDate(now);
				employee.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
				employee.setStatus(CommonLookup.STATUS_ACTIVE);
				
				wamUser.setCreatedate(now);
				wamUser.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
				wamUser.setEmployeeCode("admin");
				wamUser.setStatus(CommonLookup.STATUS_ACTIVE);
				wamUser.setPassword(WAMPasswordUtil.encrypt("erp123"));
				employee.getWAMUsers().add(wamUser);
				
				employeeAndReporting.setCreateDate(now);
				employeeAndReporting.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
				employeeAndReporting.setStatus(CommonLookup.STATUS_ACTIVE);
				employeeAndReporting.setCenterHead(employee);
				employeeAndReporting.setCompetencelead(employee);
				employeeAndReporting.setProjectManager(employee);
				employee.getEmployeeAndReportings().add(employeeAndReporting);
				
				EmployeeRole employeeRole = new EmployeeRole();
				Role role = roleDAO.getAdministratorStandardRole();
				employeeRole.setCreateDate(now);
				employeeRole.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
				employeeRole.setRole(role);
				employeeRole.setStatus(CommonLookup.STATUS_ACTIVE);
				employee.getEmployeeRoles().add(employeeRole);
				
				Employee adminHR = cloneHRAdmin();
				List<LeaveBalance> leaveBalances = getInitialLeaveBalances(adminHR);
				
				if(employeeDAO.registerEmployee(employee) != null && employeeDAO.registerEmployee(adminHR) != null && employeeDAO.assignLeaveBalance(leaveBalances) != null){
					FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO," Administrator and HR Admin registered successfully.", ""));
					REGISTERED = true;
					employee = new Employee();	
				}else{
					REGISTERED = false;
					FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR,"Registration failed.", ""));
				}
				
				
				
			}catch (Exception e) {
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR," Administrator registration failed.", e.getMessage()));
			}				
		}else{
			REGISTERED = false;
		}
	}
	
	private List<LeaveBalance> getInitialLeaveBalances(Employee employee){
		LeaveTypeDAO leaveTypeDAO = new LeaveTypeDAO();
		List<LeaveType> leaveTypes = leaveTypeDAO.getLeaveTypes();
		List<LeaveBalance> leaveBalances = new ArrayList<LeaveBalance>();
		for(LeaveType leaveType : leaveTypes){
			LeaveBalance leaveBalance = new LeaveBalance();
			if(leaveType.getLeaveType().equals(CommonLookup.SICKLEAVE_TYPE)){					 
				leaveBalance.setBalance(0F);
			 }else if(leaveType.getLeaveType().equals(CommonLookup.PRIVILIZEDLEAVE_TYPE)){
				 leaveBalance.setBalance(0F);					 
			 }else if(leaveType.getLeaveType().equals(CommonLookup.CASUALLEAVE_TYPE)){
				 leaveBalance.setBalance(0F);
				 
			 }else if(leaveType.getLeaveType().equals(CommonLookup.WORKFROMHOME_TYPE)){
				 leaveBalance.setBalance(0F);
				
			 }else if(leaveType.getLeaveType().equals(CommonLookup.OPTIONALLEAVE_TYPE)){
				 leaveBalance.setBalance(0F);
				 
			 }else{
				 leaveBalance.setBalance(0F);
				 
				 
			 }
			 leaveBalance.setCreateDate(new Date());
			 leaveBalance.setEmployee(employee);
			 leaveBalance.setLeaveType(leaveType);
			 leaveBalance.setStatus("ACTIVE");
			 leaveBalances.add(leaveBalance);
			
		 }
		return leaveBalances;
	}
	
	private Employee cloneHRAdmin() throws Exception{
		Employee employee = new Employee();
		Date now = new Date();
		employee.setEmployeeCode("adminhr");
		employee.setAuthentication(CommonLookup.AUTHENTICATION_YES);
		employee.setCreateDate(now);
		employee.setModuleName("HR");
		employee.setFirstName("HR");
		employee.setLastName("Admin");
		employee.setDesignation("Hr Executive");
		employee.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
		employee.setStatus(CommonLookup.STATUS_ACTIVE);
		
		WAMUser wamUser = new WAMUser();
		wamUser.setCreatedate(now);
		wamUser.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
		wamUser.setEmployeeCode("adminhr");
		wamUser.setPassword(WAMPasswordUtil.encrypt("erp123"));
		wamUser.setStatus(CommonLookup.STATUS_ACTIVE);
		employee.getWAMUsers().add(wamUser);
		
		EmployeeAndReporting employeeAndReporting = new EmployeeAndReporting();
		employeeAndReporting.setCreateDate(now);
		employeeAndReporting.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
		employeeAndReporting.setStatus(CommonLookup.STATUS_ACTIVE);
		employeeAndReporting.setCenterHead(employee);
		employeeAndReporting.setCompetencelead(employee);
		employeeAndReporting.setProjectManager(employee);
		employee.getEmployeeAndReportings().add(employeeAndReporting);
				
		EmployeeRole employeeRole = new EmployeeRole();
		Role role = roleDAO.getHRStandardRole();
		employeeRole.setCreateDate(now);
		employeeRole.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
		employeeRole.setRole(role);
		employeeRole.setStatus(CommonLookup.STATUS_ACTIVE);
		employee.getEmployeeRoles().add(employeeRole);
		
		return employee;
	}
	public void validateForm(){
		FORM_VALID = true;
		
		if(ValidationUtil.isEmpty(employee.getFirstName(), "First Name", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		if(ValidationUtil.isEmpty(employee.getLastName(), "Last Name", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}
		
		//-------------Password validation
		if(ValidationUtil.isEmpty(wamUser.getPassword(), "Password", null, FacesContext.getCurrentInstance()) != null){
			FORM_VALID = false;
		}else{
			//Check if reentered
			if(ValidationUtil.isReentered(reenteredPassword, "Password", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}else{
				//Check if reentered correctly
				if(wamUser.getPassword().equals(reenteredPassword)){
					
				}else{
					FORM_VALID = false;
					FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "Please reenter password correctly", ""));
				}				
			}	
		}
		//-------------End of Password validation
	}
	
	public Long getSelectedModuleId() {
		return selectedModuleId;
	}

	public void setSelectedModuleId(Long selectedModuleId) {
		this.selectedModuleId = selectedModuleId;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}
	public EmployeeAndReporting getEmployeeAndReporting() {
		return employeeAndReporting;
	}
	public void setEmployeeAndReporting(EmployeeAndReporting employeeAndReporting) {
		this.employeeAndReporting = employeeAndReporting;
	}

	public WAMUser getWamUser() {
		return wamUser;
	}
	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}

	public String getReenteredPassword() {
		return reenteredPassword;
	}

	public void setReenteredPassword(String passwordReentry) {
		this.reenteredPassword = passwordReentry;
	}

	public List<Employee> getRegisteredEmployeesList() {
		return registeredEmployeesList;
	}

	public void setRegisteredEmployeesList(List<Employee> registeredEmployeesList) {
		this.registeredEmployeesList = registeredEmployeesList;
	}

	public boolean isREGISTERED() {
		return REGISTERED;
	}

	public void setREGISTERED(boolean rEGISTERED) {
		REGISTERED = rEGISTERED;
	}	

}
